package com.gaogzhen.juc.atomic.Reference;

import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicReference;

/**
 * CAS无锁实现
 */
public class AccountDecimalCAS implements AccountDecimal {

    private final AtomicReference<BigDecimal> balance;

    public AccountDecimalCAS(BigDecimal balance) {
        this.balance = new AtomicReference<>(balance);
    }

    @Override
    public BigDecimal getBalance() {
        return balance.get();
    }

    @Override
    public void withdraw(BigDecimal amount) {
        balance.getAndUpdate(m -> m.subtract(amount));
    }

//    @Override
//    public void withdraw(BigDecimal amount) {
//        while (true) {
//            BigDecimal prev = balance.get();
//            BigDecimal next = prev.subtract(amount);
//            if (balance.compareAndSet(prev, next)) {
//                break;
//            }
//        }
//    }

}
